package com.cskaoyan.service.wx.goodsService;

import com.cskaoyan.bean.common.BaseParam;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.wx.SearchGoodsAndCategoryListVo;
import com.cskaoyan.bean.vo.wxgoodsvo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.GetInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description:todo 处理商品的逻辑
 * @Author:todo wang xv
 * @Date:todo 2022/11/22
 */
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketGoodsAttributeMapper attributeMapper;

    @Autowired
    MarketBrandMapper brandMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketGrouponRulesMapper grouponMapper;

    @Autowired
    MarketIssueMapper issueMapper;

    @Autowired
    MarketGoodsProductMapper productMapper;

    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;

    @Autowired
    MarketSystemMapper systemMapper;

    @Autowired
    MarketCollectMapper collectMapper;

    @Autowired
    MarketFootprintMapper footprintMapper;

    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    /**
     * @Description:todo 获得商品的数量
     * @Author:todo wang xv
     * @Date:todo 2022/11/22
     */
    @Override
    public Integer getGoodsNum() {
        int count = (int) goodsMapper.countByExample(null);
        Integer goodsNum = count;
        return goodsNum;
    }

    /**
     * @Description:todo 获得商品类目
     * @Author:todo wang xv
     * @Date:todo 2022/11/22
     */
    @Override
    public WxGoodsCategoryBo queryCategory(Integer id) {
        //根据id查出对应的目类；
        MarketCategory category = categoryMapper.selectByPrimaryKey(id);
        WxGoodsCategoryBo categoryBo = new WxGoodsCategoryBo();
        // 判断得到的目类是大目类还是小目类；

            if (category.getPid() == 0) {
                //此时得到的id就是大目类的id;
                categoryBo.setParentCategory(category);
                //根据当前的id查找所有相关小目类,pid
                List<MarketCategory> categories = categoryMapper.selectCategoryBy(category.getId());
                // 此时的兄弟类目
                if (categories.size()==0){
                    return categoryBo;
                }
                categoryBo.setBrotherCategory(categories);
                // 当前类目就是第一个类目;
                categoryBo.setCurrentCategory(categories.get(0));
                return categoryBo;
            } else {
                // 此时的目类就是当前目类；
                categoryBo.setCurrentCategory(category);
                // 根据当前目类找到对应的父目类
                MarketCategory fatherCategory = categoryMapper.selectByPrimaryKey(category.getPid());
                categoryBo.setParentCategory(fatherCategory);
                // 根据父目类的id找到所有pid是id的目类;
                List<MarketCategory> categories = categoryMapper.selectCategoryBy(fatherCategory.getId());
                categoryBo.setBrotherCategory(categories);
                return categoryBo;
            }


    }

    /**
     * @Description:todo 查询商品的细节；
     * @Author:todo wang xv
     * @Date:todo 2022/11/23
     */
    @Override
    public WxGoodsDetailVo queryGoodsDetail(Integer id) {
        WxGoodsDetailVo wxGoodsDetailVo = new WxGoodsDetailVo();
        // 查出相关的attribute;
        MarketGoodsAttributeExample attributeExample = new MarketGoodsAttributeExample();
        MarketGoodsAttributeExample.Criteria criteria = attributeExample.createCriteria();
        criteria.andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> attributes = attributeMapper.selectByExample(attributeExample);
        wxGoodsDetailVo.setAttribute(attributes);

        // 查出相关的goods；
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        wxGoodsDetailVo.setInfo(marketGoods);

        // 更具相关goods的brandId查Brand；
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        wxGoodsDetailVo.setBrand(marketBrand);

        // 根据goodsId查出所有的关于商品的评论个数；
        MarketCommentExample commentExample = new MarketCommentExample();
        MarketCommentExample.Criteria criteria1 = commentExample.createCriteria();
        criteria1.andValueIdEqualTo(id);
        int count = (int) commentMapper.countByExample(commentExample);
        // todo
        // 查出相关评论信息，并限制显示个数；
        String comments = "market_order_comment";
        String commentLimit = systemMapper.selectValueByName(comments);
        Integer commentLimit2 = Integer.parseInt(commentLimit);
        List<MarketComment> commentList = commentMapper.selectCommentsByValueId(id, commentLimit2);
        List<WxUserCommentVo> userCommentVos = new ArrayList<>();
        for (MarketComment comment : commentList) {
            try {
                MarketUser marketUser = userMapper.selectByPrimaryKey(comment.getUserId());
                userCommentVos.add(new WxUserCommentVo(comment.getAddTime(), comment.getAdminContent(), marketUser.getNickname(), comment.getId(), marketUser.getAvatar(), comment.getContent(), comment.getPicUrls()));
            }catch (NullPointerException e){
                e.printStackTrace();
            }
        }

        CommentsVo commentsVo = new CommentsVo(count, userCommentVos);
        wxGoodsDetailVo.setComment(commentsVo);

        // 查出相关groupon
        MarketGrouponRulesExample grouponRulesExample = new MarketGrouponRulesExample();
        MarketGrouponRulesExample.Criteria criteria2 = grouponRulesExample.createCriteria();
        criteria2.andGoodsIdEqualTo(id);
        List<MarketGrouponRules> grouponRulesList = grouponMapper.selectByExample(grouponRulesExample);
        wxGoodsDetailVo.setGroupon(grouponRulesList);

        // 查出相关的productList;
        MarketGoodsProductExample productExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria3 = productExample.createCriteria();
        criteria3.andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> products = productMapper.selectByExample(productExample);
        wxGoodsDetailVo.setProductList(products);

        // 首先更具id获得所有的规格名
        List<String> specNames = specificationMapper.getSpecName(id);

        List<SpecificationsVo> specifationlist = new ArrayList<>();
        // 再更具规格名查出对应的规格list；
        // 在将list 加到speclist里
        for (String specName : specNames) {
            MarketGoodsSpecificationExample specificationExample = new MarketGoodsSpecificationExample();
            MarketGoodsSpecificationExample.Criteria criteria4 = specificationExample.createCriteria();
            criteria4.andGoodsIdEqualTo(id);
            criteria4.andSpecificationEqualTo(specName);
            specifationlist.add(new SpecificationsVo(specName, specificationMapper.selectByExample(specificationExample)));
        }
        wxGoodsDetailVo.setSpecificationList(specifationlist);


        // 查出所有issue
        List<MarketIssue> marketIssues = issueMapper.selectByExample(null);
        wxGoodsDetailVo.setIssue(marketIssues);
        //todo 还有 share shareImage userHasCollect 没有set；
        wxGoodsDetailVo.setShare(true);
        // 查出分享图片
        wxGoodsDetailVo.setShareImage(goodsMapper.selectShareUrl(id));
        // 查出是否收藏；
        // 当前userId；


        try {
            // 添加用户足迹
            MarketUser info = GetInfo.getWxLoginInfo();
            Integer userId = info.getId();
            Integer deleted = collectMapper.selectIsCollect(id,userId);
            if (deleted==null){
                deleted=0;
            }
            wxGoodsDetailVo.setUserHasCollect(deleted);
            MarketFootprint marketFootprint = new MarketFootprint();
            marketFootprint.setAddTime(new Date());
            marketFootprint.setUserId(userId);
            marketFootprint.setGoodsId(id);
            marketFootprint.setDeleted(false);
            footprintMapper.insert(marketFootprint);
        } catch (NullPointerException e) {
            System.out.println(e);
        }


        return wxGoodsDetailVo;

    }


    /**
     * @Description:todo 用于显示关联商品
     * @Author:todo wang xv
     * @Date:todo 2022/11/23
     */
    @Override
    public RelatedGoodsVo getRelatedGoods(Integer id) {
        //获取相关联商品的类目id;
        Integer cateId = goodsMapper.selectGoodsCateId(id);
        // 查询所有目类id是cateId的商品数量；
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(cateId);
        long total = goodsMapper.countByExample(example);
        Integer limit = 6;
        List<MarketGoods> goodsList = goodsMapper.selectGoodsByCateIdLimit(cateId, limit);
        RelatedGoodsVo goodsVo = new RelatedGoodsVo();
        goodsVo.setLimit(limit);
        goodsVo.setTotal(total);
        goodsVo.setList(goodsList);
        return goodsVo;
    }

    // 根据传入的参数查找对应的商品
    @Override
    public SearchGoodsAndCategoryListVo selectGoodsByKeyword(BaseParam baseParam, MarketGoods marketGoods,String keyword) {
        PageHelper.startPage(baseParam.getPage(),baseParam.getLimit());

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        // 排序
        if (baseParam.getSort() != null && baseParam.getOrder() != null){
            marketGoodsExample.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        }else {
            marketGoodsExample.setOrderByClause("add_time desc");
        }


        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        MarketGoodsExample.Criteria criteria1 = marketGoodsExample.createCriteria();

        // 根据关键词搜索
        if (keyword != null && !StringUtils.isEmpty(keyword.trim())){
            criteria.andKeywordsLike("%" + keyword + "%");
            criteria1.andNameLike("%" + keyword + "%");

        }

        // 根据categoryId 进行搜索
        // 若categoryId 不为null 并且不为0 添加category条件
        if (marketGoods.getCategoryId() != null && marketGoods.getCategoryId() != 0){
            criteria.andCategoryIdEqualTo(marketGoods.getCategoryId());
            criteria1.andCategoryIdEqualTo(marketGoods.getCategoryId());
        }

        // 若brandId 不为null 添加 brandId 条件
        if ( marketGoods.getBrandId() != null){
            criteria.andBrandIdEqualTo(marketGoods.getBrandId());
            criteria1.andBrandIdEqualTo(marketGoods.getBrandId());
        }

        // 判断是否是新品
        if (marketGoods.getIsNew() != null){
            criteria.andIsNewEqualTo(true);
            criteria1.andIsNewEqualTo(true);
        }

        // 判断是否是热品
        if (marketGoods.getIsHot() != null){
            criteria.andIsHotEqualTo(true);
            criteria1.andIsHotEqualTo(true);
        }


        marketGoodsExample.or(criteria1);

        // 获取对应的商品
        List<MarketGoods> goods = goodsMapper.selectByExample(marketGoodsExample);
        // 获取对应的categoryId集合
        List<Integer> collect = goods.stream().map(a -> a.getCategoryId()).collect(Collectors.toList());

        List<MarketCategory> marketCategories1 = null;

        // 判断是否找到对应的商品
        if (collect.size() != 0){
            MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
            marketCategoryExample.createCriteria().andIdIn(collect);
            marketCategories1 = marketCategoryMapper.selectByExample(marketCategoryExample);
        }


        PageInfo<MarketGoods> marketGoodsPageInfo = new PageInfo<>();

        long total = marketGoodsPageInfo.getTotal();
        int pages = marketGoodsPageInfo.getPages();

        Integer page = baseParam.getPage();
        Integer limit = baseParam.getLimit();

        SearchGoodsAndCategoryListVo searchGoodsAndCategoryListVo = new SearchGoodsAndCategoryListVo();

        searchGoodsAndCategoryListVo.setLimit(limit);
        searchGoodsAndCategoryListVo.setPage(page);
        searchGoodsAndCategoryListVo.setList(goods);
        searchGoodsAndCategoryListVo.setTotal(total);
        searchGoodsAndCategoryListVo.setPages(pages);
        searchGoodsAndCategoryListVo.setFilterCategoryList(marketCategories1);

        return searchGoodsAndCategoryListVo;
    }
}
